package com.zxlfysj.search;

import java.util.Arrays;

/**
 * 斐波那契查找算法
 * @author yangshujing
 * @create 2020-08-19 11:36
 */
public class FibonacciSearch {
    public static int maxSize = 20;
    public static void main(String[] args) {
        int[] arr = {1, 8, 10, 89, 1000, 1234};
        int res = fibonacciSearch(arr, 1234);
        System.out.println(res);


    }

    //得到斐波那契数列
    public static int[] fib() {
        int[] f = new int[maxSize];
        f[0] = 1;
        f[1] = 1;
        for(int i = 2; i < maxSize; i++) {
            f[i] = f[i - 1] + f[i -2];
        }
        return f;
    }

    public static int fibonacciSearch(int[] arr, int findVal) {
        int low = 0;
        int high = arr.length - 1;
        int k = 0; //斐波那契数列的下标
        int mid = 0;
        int[] f = fib();
        while(high > f[k] - 1) {
            k++;
        }
        //获取到对应的k下标
        while(high > f[k] - 1) {
            k++;
        }

        //f[k]的值可能大于arr数组的长度，所以创建一个新数组，并用arr数组填充
        //不足部分使用arr数组的最大值进行填充，即新数组的长度要等于f[k]
        int[] temp = Arrays.copyOf(arr, f[k]);
        for(int i = high + 1; i < temp.length; i++) {
            temp[i] = arr[high];
        }

        while (low <= high) {
            mid = low + f[k - 1] - 1;
            if(findVal < temp[mid]) { //要向左边查找
                high = mid - 1;
                //因为分f[k] = f[k-1] + f[k-2];
                //即下次循环，要在分f[k-1]进行查找，即左边进行查找
                //即下次为分f[k-1] = f[k - 2] + f[k - 3]
                //所以k--
                k--;
            } else if (findVal > temp[mid]) { //要向右边查找
                low = mid + 1;
                //即要在分f[k - 2]段进行查找，
                //而f[k-2] = f[k-3] + f[k-4]
                //所以k -= 2
                k -= 2;
            } else {
                if(mid <= high) {
                    return mid;
                } else {
                    return high;
                }
            }

        }
        return -1;
    }


}
